package com.moon.interface_api.service.serviceImpl;

import com.moon.interface_api.service.RandomService;
import com.moon.interface_api.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

@Service
public class RamdomServiceImpl implements RandomService {
    
    private final String path = "D:/temp/cl";
    @Override
    public void upload(MultipartHttpServletRequest file) {
        MultipartFile pic1 = file.getFile("pic1");
        MultipartFile pic2 = file.getFile("pic2");
        File file3 = new File(path);
        if(!file3.exists()){
            file3.mkdirs();
        }
        File file1 = new File(path +"/"+ pic1.getOriginalFilename());
        File file2 = new File(path +"/"+ pic2.getOriginalFilename());
        
        try {
            InputStream in1 = pic1.getInputStream();
            InputStream in2 = pic2.getInputStream();
            FileUtils.inputstreamtofile(in1,file1);
            FileUtils.inputstreamtofile(in2,file2);
            RandomAccessFile rw = new RandomAccessFile(file2, "rw");
            FileChannel channel = rw.getChannel();
            //position  是从0开始，文件的字节位置， 最后一个参数是 结束的 字节位置，定位开始结束位置
            MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE,3L, pic1.getBytes().length);
            map.put(pic1.getBytes());
            channel.close();
        }catch (Exception e){
            throw new RuntimeException("解析失败");
        }
    }

    public boolean renameFile(File toBeRenamed, String toFileNewName) {
        //检查要重命名的文件是否存在，是否是文件
        if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {
            return false;
        }
        String p = toBeRenamed.getParent();
        File newFile = new File(p + File.separatorChar + toFileNewName);
        //修改文件名
        return toBeRenamed.renameTo(newFile);
    }
}
